<!-- <template>
    <div>
     <div style="align-items: center;height: 70px;">
      <div class="nav">
        <router-link to="/detail">收入</router-link> |
        <router-link to="/detail2">支出</router-link>
      </div>
     </div>
      <h1>This is a detail2 page</h1>
    </div>
  </template>
  
  <script>
  export default {
    name: 'Detail2View',
    inject: ['$router'],
    // ...
  }
  </script>

  <style>
  .nav {
    padding: 30px;
  }
  
  .nav a {
    font-weight: bold;
    color: #2c3e50;
  }
  
  .nav a.router-link-exact-active {
    /* color: #42b983; */
    color: white;
  }
  </style> -->

  <template>
    <div style="background-color: rgb(247, 248, 250);
      padding-top: 10px;
      min-height: 667px;">
      <!-- <div style="font-size: 15px;background-color: rgb(247,248,250);margin-top:10px"> -->
       <basic-card class="card1">
        <!-- <div class="nav"> -->
          <!-- <button @click="goBack">返回</button> -->
          <!-- <router-link to="/detail">收入</router-link> | -->
          <!-- <router-link to="/detail2">支出</router-link> -->
        <!-- </div> -->
        <!-- <van-cell title="选择单个日期" :value="date" @click="show = true" />
        <van-calendar v-model="show" :min-date="minDate" :max-date="maxDate" @confirm="onConfirm" /> -->
        <!-- <van-cell title="选择年月" :value="date" @click="show = true" style="width: 150px;"/> -->
        <div style="font-size: 15px; margin-top: 10px; padding-left:25px;display: flex;
          justify-content: space-between;">
          <span style="font-size: 15px; "> 交易明细</span>
          <span
          :value="date" @click="show = true" style="width: 150px;"
          >
            <!-- {{currentDate.getFullYear()}}年{{currentDate.getMonth()+1}}月 -->
            {{ selectYear }}年{{ selectMonth }}月
            <van-icon name="arrow-down"/>
          </span>
        </div>
        <van-popup v-model="show" position="top"
          ><div>
        <van-datetime-picker
          v-model="currentDate"
          type="year-month"
          title="选择年月"
          :min-date="minDate"
          :max-date="maxDate"
          :formatter="formatter"
          @confirm="confirmClick"
          @cancel="cancelClick"
        /></div
        ></van-popup>
        
        <div class="echart" id="mychart" :style="myChartStyle"></div>
       
        </basic-card>
      <!-- </div> -->

     <basic-card class="card2">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <!-- <van-cell v-for="item in dataDict" :key="item" :title="item" />
         -->
         <van-cell v-for="(item, index) in dataDict2" :key="index" :title="`收入：${item[0].toLocaleString()}元`" :value="`笔数：${item[1].toLocaleString()}笔`" :label="index" size="large" style="text-align: left;"/>
          
            <!-- {{ item }} - {{ yData[index] }} -->
            <!-- {{ item }} 收入：{{ yData[index] }}元 -->

            <!-- {{`${index}`}} &nbsp;&nbsp; &nbsp;&nbsp;{{ `收入：${item[0]}元` }} &nbsp;&nbsp;&nbsp;&nbsp;{{ `笔数：${item[1]}笔`
            }} -->
          <!-- </van-cell> -->
          
          <!-- <van-cell v-for="(item, index) in dataDict2" :key="index" :value="`${index}`" style="text-align: left;"> -->
            <!-- 使用 title 插槽来自定义标题 -->
            <!-- <template #title> -->
              <!-- <div> -->
                <!-- <span >{{`${index}`}}</span> -->
                <!-- <span >{{`收入：${item[0]}元`}}</span> -->
                <!-- <span>&nbsp;&nbsp;</span> -->
                <!-- <span >{{`笔数：${item[1]}笔`}}</span> -->
              <!-- </div> -->
            <!-- </template> -->
          <!-- </van-cell> -->

        </van-list>
      </basic-card>


    </div>
  </template>
    
  <script>
  import BasicCard from "../components/BasicCard.vue";
  import * as echarts from "echarts";
  import { Calendar } from 'vant';
  const monthDays = Array.from({ length: 30 }, (_, index) => index + 1);
  
  export default {
    components: { BasicCard },
    data() {
      return {
        // 年月
        // show: true,
        selectYear: 2023,
        selectMonth:8,
        // 选择日期
        date: '',
        show: false,
        // show: false,
        currentDate: new Date(),
        minDate: new Date(2022, 4, 3),
        maxDate: new Date(),
        // 列表
        list: [],
        loading: false,
        finished: false,
        // 表格数据
        xData: [], // 修改为动态计算的日期数组
        yData: [],
        zData: [],
        myChartStyle: {  width: "100%", height: "300px" },// 图表样式
        dateList: [], // 新增日期数组
        // dateList: this.$route.params.dateList.reverse(),
        dataDict:{},
        dataDict2:{},
        yyData:[],
        zzData:[],
        // 列表
        // list: [],
        // loading: false,
        // finished: false,
        // 颜色
        // color1: [
        //   "rgb(105,219,219)",
        //
        // ],
        color1: "rgb(105,219,219)",

        color2: [
          '#736f72',
          '#9a8f97',
          '#b2b2b2',
          '#c3baba',
          '#e9e3e6'
        ],
      };
    },

    async mounted() {
      await this.getData();  
      // this.initEcharts();
      this.generateDateList();
      this.initEcharts();
      // this.updateChart();
      // this.initDate();
      // this.initEcharts();
      
      // console.log(this.yData);
    },
    methods: {
      // 表
      onLoad() {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      setTimeout(() => {
        for (let i = 0; i < 10; i++) {
          this.list.push(this.list.length + 1);
        }

        // 加载状态结束
        this.loading = false;

        // 数据全部加载完成
        if (this.list.length >= 40) {
          this.finished = true;
        }
      }, 1000);
      },
      // 定义图
      initEcharts(){  
        // 基本折线图
        // const option = {
        //   xAxis: {
        //     data: this.xxData,
        //   },
        //   yAxis: {
        //     data: [],
        //     type :'value',
        //     // data: this.yyData,
        //   },
        //   grid:{
        //     left:'20',
        //     containLabel:true,
        //   },
        //   series: [
        //     {
        //       type: "bar", 
        //       data: this.yyData,
        //       itemStyle: {
        //         color: 'rgb(24, 144, 255)'
        //       },
        //       areaStyle: { // 设置阴影区域的颜色和透明度
        //         color: 'rgba(24, 144, 255, 0.3)'
        //       }
        //     }
        //   ],
          
        // };
  
        // const myChart = echarts.init(document.getElementById("mychart"));
        this.myChart = echarts.init(document.getElementById("mychart"));
        // console.log(this.xData)
        this.myChart.setOption(this.option);
  
        // // 随着屏幕大小调节图表
        // window.addEventListener("resize", () => {
        //   this.myChart.resize();
        // });
      },
      updateChart(){
        // console.log('更新啦')
        this.myChart.setOption(this.option);
        
        // // 随着屏幕大小调节图表
        // window.addEventListener("resize", () => {
        //   this.myChart.resize();
        // });
      },

      // 连接数据库
      async getData() {
        // let dataDict = {};
        // const url = "http://127.0.0.1:8081/merchanthome/details?id=1&year=2023&month=6"
        // const url = `http://127.0.0.1:8080/merchanthome/details?id=1&year=${this.selectYear}&month=${this.selectMonth}`
        const url = `/merchanthome/details?id=1&year=${this.selectYear}&month=${this.selectMonth}`
        console.log('url',url);
        const { code, data } = await this.$http.get(
          url
        );
        console.log('data',data);
        // 交易日
        const tradingDays = data.data.map(item => {
          const day = item.tradingDay.split("-")[2];
          return parseInt(day);
        });
        console.log('xData ',tradingDays);
        this.xData = tradingDays;
        // 金额
        // const incomeAmount = data.data.map(item => {
        //   const income = item.income_amount.split("-")[1];
        //   return parseInt(income);
        // });
        const incomeAmount = data.data.map(item => item.incomeAmount || 0);
        console.log('yData ',incomeAmount);
        this.yData = incomeAmount;
        // 笔数 
        // const incomeCount = data.data.map(item => {
        //   const count = item.income_count.split("-")[1];
        //   return parseInt(count);
        // });
        const incomeCount = data.data.map(item => item.incomeCount || 0);
        console.log('zData ',incomeCount);
        this.zData = incomeCount;
        // 修改格式
        // 将xData和yData、zData关联为字典
        const dataDict = this.xData.reduce((dict, x, index) => {
          dict[x] = [this.yData[index],this.zData[index]];
          return dict;
        }, {});
        this.dataDict = dataDict;

        // 打印关联后的字典
        console.log('1111',dataDict);

      },


      // 年月选择器
      async confirmClick(value) {
        this.selectYear = value.getFullYear();
        this.selectMonth = value.getMonth() + 1;
        this.show = false;
        await this.getData();
        this.generateDateList();
        // this.initEcharts();
      },
      cancelClick() {
        this.show = false;
      },
      formatter(type, val) {
      if (type === 'year') {
        return `${val}年`;
      } else if (type === 'month') {
        return `${val}月`;
      }
      return val;
      }, 

      generateDateList() {
        console.log('执行一次');
        const currentDate = new Date();
        const currentDay = currentDate.getDate();
        const currentMonth = currentDate.getMonth() + 1;
        console.log(currentDate);
        // const totalDays = new Date(this.selectYear, this.selectMonth, 0).getDate();
        // const totalDays = Math.min(currentDay, new Date(this.selectYear, this.selectMonth, 0).getDate()); 
        let totalDays;
        if (currentMonth === this.selectMonth) {
          totalDays = Math.min(currentDay, new Date(this.selectYear, this.selectMonth, 0).getDate());
        } else {
          totalDays = new Date(this.selectYear, this.selectMonth, 0).getDate();
        }
        console.log(totalDays)
        this.xxData = Array.from({ length: totalDays }, (_, index) => `${this.selectMonth}月${index + 1}日`);
        // this.xxData = Array.from({ length: totalDays }, (_, index) => `${index+1}`);
        this.xxData = this.xxData.map(date => {
          const day = date.split('月')[1].split('日')[0];
          return parseInt(day);
        });
        console.log('xxData', this.xxData);
        // console.log(this.dataDict);
        this.yyData = this.xxData.map(date => {
          const value = this.dataDict[date] ? this.dataDict[date][0] : 0;
          return value;
        });
        console.log('yyData', this.yyData);
        this.zzData = this.xxData.map(date => {
          const value = this.dataDict[date] ? this.dataDict[date][1] : 0;
          return value;
        });
        console.log('zzData', this.zzData);
        this.initEcharts();
        // this.updateChart();
        // 转换格式
        const dataDict2 = Array.from(this.xxData).reverse().reduce((dict, x, index) => {
          dict[`${this.selectMonth}月${x}日`] = [Array.from(this.yyData).reverse()[index],Array.from(this.zzData).reverse()[index]];
          return dict;
        }, {});
        // const dataDict2 = this.xxData.reduce((dict, x, index) => {
        //   dict[`${this.selectMonth}月${x}日`] = [this.yyData[index],this.zzData[index]];
        //   return dict;
        // }, {});
        this.dataDict2 = dataDict2;
        console.log('dataDict2', this.dataDict2);
        console.log('xx',this.xxData);
      },
    },
    watch: {
      color() {
        // console.log('改变颜色');
        this.updateChart();
      },
    },
    computed: {
      color(){
        // console.log('变');
        // return this.$store.state.checked ? this.color2 : this.color1
        return this.$store.state.dayBarColor[this.$store.state.styleNum]
      },
      option(){
        return{
        xAxis: {
            data: this.xxData,
          },
          yAxis: {
            data: [],
            type :'value',
            // data: this.yyData,
          },
          grid:{
            left:'20',
            containLabel:true,
          },
          series: [
            {
              type: "bar", 
              data: this.yyData,
              // itemStyle: {
              //   color: 'rgb(24, 144, 255)'
              //   // color: this.color,
              // },
              // areaStyle: { // 设置阴影区域的颜色和透明度
              //   color: 'rgba(24, 144, 255, 0.3)'
              //   // color: this.color,
              // }
            }
          ],
          color: this.color,
        };
      },
    },
  };
  </script>
    
    <!-- 文首链接 -->
  <style>
  .nav {
    padding: 30px;
  }
  
  .nav a {
    font-weight: bold;
    color: #2c3e50;
  }
  
  .nav a.router-link-exact-active {
    /* color: #42b983; */
    color: white;
  }
  /* 卡片 */
  .card1 {
  width: 340px;
  margin: 5px auto;
  /* margin-top: 10px; */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.04);
  padding: 5px 0px;
  text-align: center;

}
.card2 {
  width: 320px;
  margin: 5px auto;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.04);
  margin-top: 10px;
  margin-bottom: 10px;
  padding: 5px 10px;
  animation-name: animationCard2;
  animation-duration: 0.7s;

}
@keyframes animationCard2 {
  0% {
    transform: translateY(200px);
  }
  100% {
    transform: translateY(0);
  }
  }

  </style>
    